package cn.commander.utils;

import org.springframework.beans.BeansException;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.ImportResource;
import org.springframework.stereotype.Component;

/**
 * @ClassName:SpringPropertiesUtil
 * @Description: spring配置文件工具
 * @Created by:
 * @Date: 2016/7/7 15:06
 * @Version: 1.0
 */
@Component
@ConfigurationProperties(prefix="surpass.info")
@ImportResource("classpath:/spring/message-bean.xml")
public class SpringPropertiesUtils implements ApplicationContextAware {

	public static final String KEY = "propertyConfigurer";
	private static ApplicationContext applicationContext;

	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringPropertiesUtils.applicationContext = applicationContext;
	}

	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	/**
	 * 获取配置文件中的内容
	 *
	 * @param keyName
	 * @return
	 */
	@SuppressWarnings("static-access")
	public static String parseStr(String keyName) {
		CustomizedPropertyPlaceholderConfigurer cp = (CustomizedPropertyPlaceholderConfigurer) applicationContext
				.getBean(KEY);
		return cp.getContextProperty(keyName).toString();
	}

	/**
	 * 获取配置文件中的内容
	 *
	 * @param keyName
	 * @return
	 */
	@SuppressWarnings("static-access")
	public static int parseInt(String keyName) {
		CustomizedPropertyPlaceholderConfigurer cp = (CustomizedPropertyPlaceholderConfigurer) applicationContext
				.getBean(KEY);
		return Integer.parseInt(cp.getContextProperty(keyName).toString());
	}

	/**
	 * 获取配置文件中的内容
	 *
	 * @param keyName
	 * @return
	 */
	@SuppressWarnings("static-access")
	public static double parseDouble(String keyName) {
		CustomizedPropertyPlaceholderConfigurer cp = (CustomizedPropertyPlaceholderConfigurer) applicationContext
				.getBean(KEY);
		return Double.parseDouble(cp.getContextProperty(keyName).toString());
	}
}